<!--
 * @Author: gy
 * @Date: 2019-12-24 15:13:01
 * @LastEditors  : wl
 * @LastEditTime : 2020-06-17 17:39:10
 -->
<!--  -->
<template>
  <div class="layout-content">
    <el-form ref="form" :model="form" :rules="rules" label-width="110px">
      <!--prop="parent_dept_name"  -->
      <el-form-item label="部门名称">
        <el-input v-model="form['parent_dept_name']" @focus="dialogVisibleDepart = true" placeholder="请选择部门名称" />
        <!-- <div class="select-depart" @click="dialogVisibleDepart = true">{{ treeObj.label ? treeObj.label: '选择部门' }}</div> -->
        <div v-if="dialogVisibleDepart">
          <el-dialog
            title="部门选择"
            :visible.sync="dialogVisibleDepart"
            width="30%"
            :destroy-on-close="true"
            :append-to-body= "true"
            top="30vh"
            :modal-append-to-body= "false"
            @close="dialogVisibleDepart = false">
            <div class="search-content">
              <div class="search-box">
                <el-input
                  placeholder="输入关键字进行过滤"
                  v-model="filterText">
                </el-input>
                <span class="search-btn" @click="searchTreeData">查询</span>
              </div>
              <div class="tree-box">
                <div class="tree-fold">
                  <span @click="foldTree">折叠</span>
                  <i> / </i>
                  <span @click="openTree">打开</span>
                </div>
                <el-tree
                  class="filter-tree"
                  :data="treeData"
                  :props="defaultProps"
                  :default-expand-all="expanded"
                  :default-checked-keys="checkedKeys"
                  :check-strictly="true"
                  show-checkbox
                  node-key="id"
                  @check="treeCheck"
                  node-click="nodeClick"
                  @check-change="handleMetaNodeClick"
                  :filter-node-method="filterNode"
                  ref="tree">
                </el-tree>
              </div>
            </div>
            <!-- <el-cascader
              v-model="form['parent_id']"
              :options="menuList"
              :props="props"
              collapse-tags
              ref="menu"
              placeholder="请选择部门"
              :show-all-levels="false"
              clearable></el-cascader> -->
            <span slot="footer" class="dialog-footer">
              <el-button @click="selectDepartCancel">取 消</el-button>
              <el-button type="primary" @click="selectDepartConfirm">确 定</el-button>
            </span>
          </el-dialog>
        </div>
      </el-form-item>
      <!-- <el-form-item label="上级部门" prop="parent_dept_id">
        <el-cascader
          v-model="form['parent_dept_id']"
          :options="menuList"
          :props="props"
          collapse-tags
          ref="menu"
          :placeholder="form['parent_dept_name'] ? form['parent_dept_name'] : '请选择部门'"
          :show-all-levels="false"
          clearable></el-cascader>
      </el-form-item> -->
      <el-form-item label="部门名称" prop="dept_name">
        <el-input v-model="form['dept_name']" placeholder="请输入部门名称" @blur="departNameCheck"/>
        <span class="errorText" v-show="form['checkParam']['uniqueDepartName']">该部门名称重复</span>
      </el-form-item>
      <el-form-item label="显示顺序">
        <el-input type="number" v-model.number="form['order_num']" placeholder="请输入显示顺序" />
      </el-form-item>
      <el-form-item label="负责人">
        <el-input v-model="form['leader']" placeholder="请输入负责人" />
      </el-form-item>
      <el-form-item label="联系电话">
        <el-input v-model="form['phone']" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form['email']" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="部门状态" prop="status">
        <el-radio-group v-model="form['status']">
          <el-radio label="0">正常 </el-radio>
          <el-radio label="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- <div class="handle-btn">
      <el-button type="primary" @click="handleConfirm">确定</el-button>
      <el-button @click="handleCancel">关闭</el-button>
    </div> -->
  </div>
</template>

<script>
import {
  getGetDeptTreeData, //获取部门树
  getRoleDeptTreeData, // 由角色id获取对应部门树
  checkDeptNameUnique // 菜单名唯一性
} from '@/api/api'
import SystemMixin from '@/mixins/SystemMixin'
export default {
  name: 'AddMenu',
  props: {
    titles: {
      type: String,
      default: () => ''
    }
  },
  mixins: [SystemMixin],
  data() {
    let parentId = (rule, value, fn) => {
      let idList = this.$refs['menu'].getCheckedNodes();
      if(idList.length === 0) {
        fn(new Error('请选择上级部门'))
      } else {
        fn();
      }
    };
    return {
      dialogVisibleDepart: false,
      editCheckId: '', // 单选
      filterText: '',
      treeData: [], // tree树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      expanded: '', // 折叠打开
      checkedKeys: [], // 默认打开的
      form: {
        parent_dept_id: '',
        parent_dept_name: '',
        dept_name: '',
        order_num: null,
        leader: '',
        phone: '',
        email: '',
        status: '0', // 部门状态
        // 唯一性检测
        checkParam: {
          uniqueDepartName: false
        },
      },

      // checkRepeatParam: {
      //   url: '/system/api/Menu/CheckMenuNameUnique',
      //   param: 'menu_name',
      //   // parent_id
      //   methods: 'get'
      // },
      // // 查询菜单信息(包含父元素)
      // menuParentInfo: {},
      menuList:[],
      moduleHidden: false,
      menuForParentName: '',
      props: { multiple: true },
      rules: {
        parent_dept_name: [
          {
            trigger: 'change',
            required: true,
            trigger: 'blur'
          }
        ],
        dept_name: [
          {
            required: true,
            message: '请输入菜单名称',
            trigger: 'blur'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ]
      }
    }
  },
  mounted() {
    // // 上级菜单-子集菜单新增
    // getMenuForParent({ pid: ''}).then(res => {
    //   if(res.code === 0) {
    //     // 查询菜单信息
    //     this.menuParentInfo = res['data'] ? res['data'] : {}
    //     // this.menuForParentName = res['data']['parent_name'] ? res['data']['parent_name'] : '系统管理'
    //   }
    // })
    // 部门树
    getGetDeptTreeData().then(res => {
      if(res.code === 0) {
        this.treeData = this.assembleTreeData(res.data, "id", "pId");
      }
    })
    // // 由角色获取对应菜单
    // getRoleDeptTreeData({roleId:this.uid}).then(res => {
    //   if(res.code === 0) {
    //     // this.menuList = res.data
    //     console.log(res, 'getRoleDeptTreeData')
    //   }
    // })
  },
  methods: {
    // 过滤
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    searchTreeData() {
      clearTimeout(this.timeOut)
      this.timeOut = setTimeout(() => {
        this.$refs.tree.filter(this.filterText);
      }, 500)
    },
    // 实现单选
    handleMetaNodeClick(item, node, self) {
      if(node === true) {
        this.editCheckId = item.id
        this.$refs['tree'].setCheckedKeys([item.id])
      } else {
        if(this.editCheckId === item.id) {
          this.$refs['tree'].setCheckedKeys([item.id])
        }
      }
    },
    nodeClick(item, node, self) {
      this.editCheckId = item.id
      this.$refs['tree'].setCheckedKeys([item.id])
    },
    // 选择
    treeCheck(item, data) {
      console.log(item, 'treeCheck')
      this.treeObj = {
        id: item.id,
        label: item.name
      }
      this.form['parent_dept_name'] = this.treeObj['label']
      // console.log(this.form['parent_dept_name'], `this.form['parent_dept_name']`)
      // console.log(this.form['parent_dept_name'], `this.form['parent_dept_name']`)
    },
    // tree-展开
    openTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree)
        // for (let i = 0; i < treeList.length; i++) {
        //   console.log(this.$refs['tree'].store.nodesMap[treeList[i].id])
        //   // this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = false
        // }
      })
    },
    // tree-收缩
    foldTree() {
      let treeList = this.data;
      this.$nextTick(() => {
        console.log(this.$refs.tree)
        // console.log(this.$refs.tree.store._getAllNodes().length)
        // // for (let i = 0; i < treeList.length; i++) {
        // //   this.$refs['tree'].store.nodesMap[treeList[i].id].expanded = true
        // // }
      })
    },
    // 部门选择-确认
    selectDepartConfirm() {
      this.form['parent_dept_id'] = this.treeObj['id']
      // console.log(this.form['parent_dept_name'])
      this.dialogVisibleDepart = false;
    },
    // 部门选择-取消
    selectDepartCancel() {
      this.treeObj = {}
      this.dialogVisibleDepart = false;
    },
    // 部门唯一性
    async departNameCheck() {
      if(this.form['dept_name'] === '') {
        this.form['checkParam']['uniqueDepartName'] = false
      } else {
        this.form['checkParam']['uniqueDepartName'] = await this.checkUnique(
          '/system/api/Dept/CheckDeptNameUnique',
          { 'dept_name': this.form['dept_name'],'parent_id':this.form['parent_dept_id']});
      }
    },
  },
  watch: {
    titles: {
      handler(val) {
        if (val === '新增') {
          this.moduleHidden = false
        } else {
          this.moduleHidden = true
        }
      },
      immediate: true
    },
    "form.parent_dept_id": {
      handler(val) {
        this.checkedKeys[0] = val
      },
      immediate: true
    },
    // checkedKeys
    // // 过滤字段
    // filterText(val) {
    //   this.$refs.tree.filter(val);
    // },
    // 部门弹窗监听
    dialogVisibleDepart: {
      handler(val) {
        if(!val) {
          this.filterText = ''
          this.editCheckId = ''
          // this.treeObj = {}
        }
      },
      immediate: true
    },
    // 如果是子集新增存在id可查找父级
    'form.ids': {
      handler(val) {
        if(val) {
          // getMenuForParent({ pid: val}).then(res => {
          //   if(res.code === 0) {
          //     // 查询菜单信息
          //     this.menuParentInfo = res['data'] ? res['data'] : {}
          //     // this.menuForParentName = res['data']['parent_name'] ? res['data']['parent_name'] : '系统管理'
          //   }
          // })
        } else {
          // 菜单树(全部)
          // getMenuTreeData().then(res => {
          //   if(res.code === 0) {
          //     this.menuList = res.data
          //     console.log(res, 'getMenuTreeData')
          //   }
          // })
        }
        console.log(val, 'form.ids')
      },
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
.select-depart {
  width:107px;
  line-height:34px;
  background:linear-gradient(0deg,rgba(70,127,255,1),rgba(126,166,253,1));
  box-shadow:0px 5px 7px 0px rgba(213,215,218,0.9);
  border-radius:4px;
  color:rgba(255,255,255,1);
  text-align: center;
  cursor: pointer;
}
</style>
